#include "cmdshell.h"
#include <stdio.h>
#include <string.h>
#include "ipctools.h"

static cmd_shell_t g_btools_cmds[] = {
	{"dumpregs",   CMD_ENABLE,  dumpregs,   0 },
	{"bspmd",      CMD_ENABLE,  bspmd,      0 },
	{"bspmm",      CMD_ENABLE,  bspmm,      0 },
	{ NULL,        CMD_DISABLE, NULL,       0 },
};

static const cmd_shell_t *cmd_shell_search(const char *cmdstr, const cmd_shell_t *p_cmds)
{
	if (p_cmds == NULL || cmdstr == NULL)
		return NULL;

	size_t len_cmd_str = strlen(cmdstr);
	if (len_cmd_str == 0) {
		printf("cmdstr is zero length string \n");
		return NULL;
	}

	/**/
	int i = 0;
	while (p_cmds[i].cmdstr) {
		if (strcmp(p_cmds[i].cmdstr, cmdstr) == 0)
			return (&p_cmds[i]);
		i++;
	}
	printf("cann't find cmd: %s \n", cmdstr);
	return NULL;
}

int cmd_shell_run(int argc, char *argv[], const cmd_shell_t *p_cmds)
{
	const cmd_shell_t *p_cmd = NULL;
	char *p_cmd_str = NULL;
	char *p_tmp = NULL;

	if (argv == NULL || p_cmds == NULL)
	{
		return -1;
	}

	p_cmd_str = argv[0];

	for (p_tmp = p_cmd_str; *p_tmp != '\0';) {
		if (*p_tmp++ == '/')
		{
			p_cmd_str = p_tmp;
		}
	}
	printf("cmdstr:%s\n", p_cmd_str);

	p_cmd = cmd_shell_search(p_cmd_str, (cmd_shell_t *)p_cmds);
	if (p_cmd == NULL) {
		printf("cann't find cmdstr:%s\n", argv[0]);
		return -1;
	} else {
		if (p_cmd->p_func == NULL)
		{
			return -2;
		}
		return ((int)p_cmd->p_func(argc, argv));
	}

	return 0;
}


int main(int argc, char *argv[])
{
	int bsp_do;
	char *p_cmd_str = argv[0];
	char *p_tmp = NULL;

	for (p_tmp = p_cmd_str; *p_tmp != '\0';) {
		if (*p_tmp++ == '/')
			p_cmd_str = p_tmp;
	}

	if (0 == strcmp(p_cmd_str, "ipctools"))
	{
		argc--;
		bsp_do = cmd_shell_run(argc, &argv[1], (cmd_shell_t *)g_btools_cmds);
	}
	else 
	{
		bsp_do = cmd_shell_run(argc, argv, (cmd_shell_t *)g_btools_cmds);
	}
	if (0 != bsp_do)
		printf("\ndo errro\n");
    
	printf("[END]\n");
	fflush(stdout);

	return 0;
}